package master

import (
	"fmt"
	"github.com/hwcer/cosgo/registry"
	"github.com/hwcer/yyds/context"
	"server/game/model"
	"strconv"
	"strings"
)

func init() {
	Register(&Mail{})
}

type Mail struct {
}

func (this *Mail) Caller(node *registry.Node, handle *context.Context) interface{} {
	f := node.Method().(func(*Mail, *context.Context) interface{})
	return f(this, handle)
}

// Page 获取邮件
func (this *Mail) Page(c *context.Context) interface{} {
	page := &Paging{}
	if err := c.Bind(page); err != nil {
		return err
	}
	rows := make([]*model.Mail, 0)
	page.Rows = &rows
	page.Init(100)
	tx := db.Order("update", -1)
	if page.Key != "" {
		if page.Value == "" {
			return c.Error("请输入查询内容")
		}
		if page.Key == "uid" {
			if uid, err := strconv.Atoi(page.Value); err == nil {
				tx = tx.Where(uint64(uid))
			} else {
				return err
			}
		} else if page.Key == "iid" {
			if iid, err := strconv.Atoi(page.Value); err == nil {
				tx = tx.Where("iid", int32(iid))
			} else {
				return err
			}
		} else {
			query := fmt.Sprintf("%s = ?", page.Key)
			tx = tx.Where(query, page.Value)
		}
	}
	if tx = tx.Model(&model.Mail{}).Page(&page.Paging); tx.Error != nil {
		return tx.Error
	}
	var data []map[string]interface{}
	for _, v := range rows {
		data = append(data, v.Display())
	}
	page.Paging.Rows = data
	return page.Paging
}

type MailCreateArgs struct {
	model.Mail
	model.MailText
	XID  string   `json:"xid"` //避免重复发送
	Uid  []string `json:"uid"`
	Attr []int32  `json:"attr"`
}

func (this *Mail) Create(c *context.Context) interface{} {
	args := new(MailCreateArgs)
	if err := c.Bind(args); err != nil {
		return err
	}
	if len(args.Uid) == 0 {
		return c.Error("uid empty")
	}
	if args.XID == "" {
		args.XID = strconv.FormatUint(uint64(c.Unix()), 32)
	}

	args.Create = c.Unix()
	args.Update = args.Create
	args.Mail.Text = &args.MailText
	for i := 0; i < len(args.Attr); i += 2 {
		j := i + 1
		if j < len(args.Attr) {
			args.Mail.AddAttr(args.Attr[i], args.Attr[j])
		}
	}
	var rows []*model.Role
	if tx := db.Select("_id", "name").Where(args.Uid).Find(&rows); tx.Error != nil {
		return tx.Error
	}
	if len(rows) == 0 {
		return c.Errorf(0, "user not found:%v", args.Uid)
	}
	abnormal := map[string]string{}
	var success []string
	us := map[string]*model.Role{}
	for _, v := range rows {
		us[v.Uid] = v
	}

	for _, uid := range args.Uid {
		v, ok := us[uid]
		if !ok {
			abnormal[uid] = "用户不存在"
		} else {
			m := args.Mail.Clone(v.Uid, args.XID)
			if err := m.Save(args.XID); err != nil {
				abnormal[v.Uid] = err.Error()
			} else {
				success = append(success, uid)
			}
		}
	}
	if len(abnormal) > 0 {
		s := strings.Builder{}
		s.WriteString("以下用户发送邮件失败")
		for k, v := range abnormal {
			s.WriteString("\n")
			s.WriteString(fmt.Sprintf("%s : %s", k, v))
		}
		return c.Errorf(0, s.String())
	}

	//发消息
	if len(success) > 0 {
		notify := &struct {
			Mail int8 `json:"mail"`
		}{
			Mail: 1,
		}
		for _, v := range success {
			_ = Send(v, notify, "S2CNotify")
		}
	}

	return true
}
